const execSQL = require("../../db/mysql");
async function add(form) {
    try {
        let sql =
            "insert into address(userID,consignee,address,tel,postcode,isdefault) values(?,?,?,?,?,?)";
        let sqlParams = [
            form.userID,
            form.consignee,
            form.address,
            form.tel,
            form.postcode,
            form.isdefault === "" ? 0 : form.isdefault,
        ];
        // 
        const data = await execSQL(sql, sqlParams);
        return {
            code: 1,
            msg: "添加成功!",
        };
    } catch (error) {
        return {
            code: 0,
            msg: "添加失败",
        };
    }
}
async function select(userID) {
    try {
        let sql = "select * from address  where userID=?";
        let sqlParams = [userID];
        const data = await execSQL(sql, sqlParams);
        return {
            code: 1,
            msg: "查询成功",
            result: data,
        };
    } catch (error) {
        return {
            code: 0,
            msg: "查询失败",
        };
    }
}
async function update(form) {
    try {
        let sql =
            "update address set consignee=?,address=?,tel=?,postcode=?,isdefault=? where userID=? and id=?";
        let sqlParams = [
            form.consignee,
            form.address,
            form.tel,
            form.postcode,
            Number(form.isdefault),
            form.userID,
            form.id,
        ];
        
        const data = await execSQL(sql, sqlParams);
        if (data.affectedRows > 0) {
            return {
                code: 1,
                msg: "修改成功",
            };
        }
        else {
            return {
                code: 0,
                msg: "修改失败",
            };
        }
    } catch (error) {
        return {
            code: 0,
            msg: "修改失败",
        };
    }
}

async function del(form) {
    try {
        let sql = "delete from address where userID=? and id=?";
        let sqlParams = [form.userID, form.id];
        const data = await execSQL(sql, sqlParams);
        
        if (data.affectedRows > 0) {
            return {
                code: 1,
                msg: "删除成功",
            };
        }
        else {
            return {
                code: 0,
                msg: "删除失败",
            };
        }
        
    } catch (error) {
        return {
            code: 0,
            msg: "删除失败",
        };
    }
}

module.exports = { add, select, update, del };
